//
//  ChongZhiViewController.m
//  ZhiBoYuan
//
//  Created by coder_di on 2018/4/24.
//  Copyright © 2018年 apple. All rights reserved.
//

#import "ChongZhiViewController.h"
#import "ChongzhiTableViewCell.h"
#import "AFAppDotNetAPIClient.h"
#import "WebViewController.h"

# import <AlipaySDK/AlipaySDK.h>//支付宝
#import "WXApi.h"//微信


#import <ifaddrs.h>
#import <arpa/inet.h>
#import <net/if.h>

#define IOS_CELLULAR    @"pdp_ip0"
#define IOS_WIFI        @"en0"
#define IOS_VPN         @"utun0"
#define IP_ADDR_IPv4    @"ipv4"
#define IP_ADDR_IPv6    @"ipv6"

@interface ChongZhiViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UITextFieldDelegate>

@property (nonatomic, strong)UICollectionViewFlowLayout *flowLayout;//按钮布局


@property (nonatomic, strong)NSArray *dataArray;

@property (nonatomic,weak) UICollectionView *collectionView;

@property (nonatomic, strong)NSString *xuanzhong;

@property (nonatomic, strong)UIButton *jineBtn;

@property (nonatomic, strong)UITextField *chongZHiTextField;

@property (nonatomic, strong)NSString *money;

@property (nonatomic, strong)NSString *zhiFuUrl;//跳转到支付页面的url

@property (nonatomic, assign)int ZhiFuFangShi;

@property (nonatomic, strong)NSDictionary *zhifuDic;//支付宝支付的字符串

@property (nonatomic, strong)NSDictionary *weiChatPayDic;//微信支付参数

@end

@implementation ChongZhiViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.title = @"学豆充值";
    
    _money = @"100";
    
    _dataArray = @[@"100学豆",@"50学豆",@"20学豆",@"10学豆"];
    
    _xuanzhong = @"100学豆";
    
    [self setUI];
    
}

//去充值
-(void)quchongZhiAction{
    if (_ZhiFuFangShi == 1) {
//微信支付
        [self weChatPay];
        
    }else if (_ZhiFuFangShi== 2){
//支付宝支付
        [self zhiFuBaopay];
        
    }else{
//银行卡支付
        [self yinhangkaPay];
    }
}

//微信支付
-(void)weChatPay{
    // 判断手机有没有微信
    if ([WXApi isWXAppInstalled]) {
        _weiChatPayDic = [NSDictionary dictionary];
        
        [MBProgressHUD showLoadingImageToView:self.view];
        float aa = [NSString stringWithFormat:@"%.2f",[_money floatValue]].floatValue;
        if (1 > aa * 100) {
            [MBProgressHUD showTextOnly:self.view message:@"最低充值金额不能低于0.01元" delay:2.0];
            return;
        }
        
        SGParameter *parameter  = [[SGParameter alloc] init];
        parameter.body = @{
                           @"amount":[NSString stringWithFormat:@"%.2f",[_money floatValue]]                       };
        
        [SGHttpTool POST:[NSString stringWithFormat:@"%@g=client&m=pay&a=appWxPay",HTTPP] parameter:parameter sucess:^(id responseObject) {
            NSLog(@"%@",responseObject);
            
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            
            if ([responseObject[@"status"] intValue] == 200) {
                _weiChatPayDic = responseObject[@"data"][@"alipay_info"];
                //调微信支付
                [self weChatPayAction];
            
            }else{
                [MBProgressHUD showTextOnly:self.view message:responseObject[@"msg"] delay:2.0];
            }
            
        } failure:^(NSError *error) {
            NSLog(@"%@",error);
            
        }];
        
    }else{
        [MBProgressHUD showTextOnly:self.view message:@"请先去安装微信客户端" delay:2.0];
    }
    
    
    
}
//微信支付
-(void)weChatPayAction{
    NSLog(@"%@",_weiChatPayDic);
    //需要创建这个支付对象
    PayReq *req   = [[PayReq alloc] init];
    //由用户微信号和AppID组成的唯一标识，用于校验微信用户
    req.openID = [_weiChatPayDic valueForKey:@"appid"];
    // 商家id，在注册的时候给的
    req.partnerId = [_weiChatPayDic valueForKey:@"partnerid"];
    // 预支付订单这个是后台跟微信服务器交互后，微信服务器传给你们服务器的，你们服务器再传给你
    req.prepayId  = [_weiChatPayDic valueForKey:@"prepayid"];
    // 根据财付通文档填写的数据和签名
    req.package  = [_weiChatPayDic valueForKey:@"package"];
    // 随机编码，为了防止重复的，在后台生成
    req.nonceStr  = [_weiChatPayDic valueForKey:@"noncestr"];
    // 这个是时间戳，也是在后台生成的，为了验证支付的
    NSString * stamp = [_weiChatPayDic valueForKey:@"timestamp"];
    req.timeStamp = stamp.intValue;
    // 这个签名也是后台做的
    req.sign = [_weiChatPayDic valueForKey:@"sign"];
    //发送请求到微信，等待微信返回onResp
    [WXApi sendReq:req];
    
}
//支付宝支付
-(void)zhiFuBaopay{
    
    _zhifuDic = [NSDictionary dictionary];
    
    [MBProgressHUD showLoadingImageToView:self.view];
    float aa = [NSString stringWithFormat:@"%.2f",[_money floatValue]].floatValue;
    if (1 > aa * 100) {
        [MBProgressHUD showTextOnly:self.view message:@"最低充值金额不能低于0.01元" delay:2.0];
        return;
    }
    
    SGParameter *parameter  = [[SGParameter alloc] init];
    parameter.body = @{
                       @"amount":[NSString stringWithFormat:@"%.2f",[_money floatValue]]                       };
    
    [SGHttpTool POST:[NSString stringWithFormat:@"%@g=client&m=pay&a=appAlipay",HTTPP] parameter:parameter sucess:^(id responseObject) {
        NSLog(@"%@",responseObject);
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        
        if ([responseObject[@"status"] intValue] == 200) {
            
            _zhifuDic = responseObject;
            
            [self aliPayAction];

        }else{
            [MBProgressHUD showTextOnly:self.view message:responseObject[@"msg"] delay:2.0];
        }
        
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
        
    }];

}

//调用支付宝去支付
-(void)aliPayAction{
    //应用注册scheme,在AliSDKDemo-Info.plist定义URL types
    NSString *appScheme = @"2018011601907915";
    NSString * orderString = _zhifuDic[@"data"][@"alipay_info"];
    // NOTE: 调用支付结果开始支付
    [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
//        NSLog(@"reslut = %@",resultDic);

    }];
    
}

//银行卡支付
-(void)yinhangkaPay{
    [MBProgressHUD showLoadingImageToView:self.view];
    //获取ip
    NSString *ipUrl = [self getIPAddress:NO];
    float aa = [NSString stringWithFormat:@"%.2f",[_money floatValue]].floatValue;
    if (1 > aa * 100) {
        [MBProgressHUD showTextOnly:self.view message:@"最低充值金额不能低于0.01元" delay:2.0];
        return;
    }
    
    SGParameter *parameter  = [[SGParameter alloc] init];
    parameter.body = @{
//                       @"directpaytype":@"1",
                       @"amount":[NSString stringWithFormat:@"%.2f",[_money floatValue]],
                       @"userip":ipUrl
                       };
    
    [SGHttpTool POST:[NSString stringWithFormat:@"%@g=Client&m=pay&a=PayMobile",HTTPP] parameter:parameter sucess:^(id responseObject) {
        NSLog(@"%@",responseObject);
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        
        if ([responseObject[@"status"] intValue] == 200) {
            
            _zhiFuUrl = [responseObject[@"data"] valueForKey:@"payurl"];
            
            WebViewController *chongZHiWebVC = [[WebViewController alloc]init];
            chongZHiWebVC.url = _zhiFuUrl;
            [self.navigationController pushViewController:chongZHiWebVC animated:YES];
            
        }else{
            [MBProgressHUD showTextOnly:self.view message:responseObject[@"msg"] delay:2.0];
        }
        
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
        
    }];
    
}

#pragma mark - 获取设备当前网络IP地址
- (NSString *)getIPAddress:(BOOL)preferIPv4
{
    NSArray *searchArray = preferIPv4 ?
    @[ IOS_VPN @"/" IP_ADDR_IPv4, IOS_VPN @"/" IP_ADDR_IPv6, IOS_WIFI @"/" IP_ADDR_IPv4, IOS_WIFI @"/" IP_ADDR_IPv6, IOS_CELLULAR @"/" IP_ADDR_IPv4, IOS_CELLULAR @"/" IP_ADDR_IPv6 ] :
    @[ IOS_VPN @"/" IP_ADDR_IPv6, IOS_VPN @"/" IP_ADDR_IPv4, IOS_WIFI @"/" IP_ADDR_IPv6, IOS_WIFI @"/" IP_ADDR_IPv4, IOS_CELLULAR @"/" IP_ADDR_IPv6, IOS_CELLULAR @"/" IP_ADDR_IPv4 ] ;

    NSDictionary *addresses = [self getIPAddresses];
    NSLog(@"addresses: %@", addresses);

    __block NSString *address;
    [searchArray enumerateObjectsUsingBlock:^(NSString *key, NSUInteger idx, BOOL *stop)
     {
         address = addresses[key];
         //筛选出IP地址格式
         if([self isValidatIP:address]) *stop = YES;
     } ];
    return address ? address : @"0.0.0.0";
}

- (BOOL)isValidatIP:(NSString *)ipAddress {
    if (ipAddress.length == 0) {
        return NO;
    }
    NSString *urlRegEx = @"^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
    "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
    "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
    "([01]?\\d\\d?|2[0-4]\\d|25[0-5])$";

    NSError *error;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:urlRegEx options:0 error:&error];

    if (regex != nil) {
        NSTextCheckingResult *firstMatch=[regex firstMatchInString:ipAddress options:0 range:NSMakeRange(0, [ipAddress length])];

        if (firstMatch) {
            NSRange resultRange = [firstMatch rangeAtIndex:0];
            NSString *result=[ipAddress substringWithRange:resultRange];
            //输出结果
            NSLog(@"%@",result);
            return YES;
        }
    }
    return NO;
}

- (NSDictionary *)getIPAddresses
{
    NSMutableDictionary *addresses = [NSMutableDictionary dictionaryWithCapacity:8];

    // retrieve the current interfaces - returns 0 on success
    struct ifaddrs *interfaces;
    if(!getifaddrs(&interfaces)) {
        // Loop through linked list of interfaces
        struct ifaddrs *interface;
        for(interface=interfaces; interface; interface=interface->ifa_next) {
            if(!(interface->ifa_flags & IFF_UP) /* || (interface->ifa_flags & IFF_LOOPBACK) */ ) {
                continue; // deeply nested code harder to read
            }
            const struct sockaddr_in *addr = (const struct sockaddr_in*)interface->ifa_addr;
            char addrBuf[ MAX(INET_ADDRSTRLEN, INET6_ADDRSTRLEN) ];
            if(addr && (addr->sin_family==AF_INET || addr->sin_family==AF_INET6)) {
                NSString *name = [NSString stringWithUTF8String:interface->ifa_name];
                NSString *type;
                if(addr->sin_family == AF_INET) {
                    if(inet_ntop(AF_INET, &addr->sin_addr, addrBuf, INET_ADDRSTRLEN)) {
                        type = IP_ADDR_IPv4;
                    }
                } else {
                    const struct sockaddr_in6 *addr6 = (const struct sockaddr_in6*)interface->ifa_addr;
                    if(inet_ntop(AF_INET6, &addr6->sin6_addr, addrBuf, INET6_ADDRSTRLEN)) {
                        type = IP_ADDR_IPv6;
                    }
                }
                if(type) {
                    NSString *key = [NSString stringWithFormat:@"%@/%@", name, type];
                    addresses[key] = [NSString stringWithUTF8String:addrBuf];
                }
            }
        }
        // Free memory
        freeifaddrs(interfaces);
    }
    return [addresses count] ? addresses : nil;
}

-(void)setUI{
    //设置布局对象
    _flowLayout = [[UICollectionViewFlowLayout alloc]init];
    //设置item大小
    _flowLayout.itemSize = CGSizeMake((ScreenWidth - 60)/2, 50*KscreenHeight);
    //    //设置最小列间距
    _flowLayout.minimumInteritemSpacing = 0 * KscreenWidth;
    //设置最小行间距
    _flowLayout.minimumLineSpacing = 20 * KscreenHeight;
    //设置每个分区边缘位置(上左下右)
    _flowLayout.sectionInset = UIEdgeInsetsMake(0 * KscreenWidth, 0 * KscreenHeight, 0 * KscreenWidth, 0 * KscreenHeight);
    
    UICollectionView *collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, NAVIGATION_BAR_HEIGHT + 70 * KscreenHeight, ScreenWidth, Screenheight - NAVIGATION_BAR_HEIGHT - 70 * KscreenHeight ) collectionViewLayout:_flowLayout];
    if (@available(iOS 11.0, *)) {
        collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    collectionView.delegate = self;
    collectionView.backgroundColor = [UIColor whiteColor];
    //设置数据源
    collectionView.dataSource = self;
    collectionView.alwaysBounceVertical = YES;
        collectionView.scrollEnabled = NO;
    //注册
    [collectionView registerClass:[ChongzhiTableViewCell class] forCellWithReuseIdentifier:@"ChongzhiTableViewCell"];
    
    //添加到视图
    [self.view addSubview:collectionView];
    _collectionView = collectionView;
    
    
    UILabel *lable = [[UILabel alloc]initWithFrame:CGRectMake(20 * KscreenWidth, 30 * KscreenHeight + NAVIGATION_BAR_HEIGHT, 100 * KscreenWidth, 20 * KscreenHeight)];
    lable.text = @"充值金额";
    lable.textAlignment = NSTextAlignmentLeft;
    lable.font = [UIFont systemFontOfSize:15 * KscreenWidth];
    [self.view addSubview:lable];

     _chongZHiTextField = [[UITextField alloc]initWithFrame:CGRectMake(20 * KscreenWidth, 205 * KscreenHeight + NAVIGATION_BAR_HEIGHT, (ScreenWidth - 60 * KscreenWidth)/2, 50 * KscreenHeight)];
    _chongZHiTextField.backgroundColor = hui1Color;
    _chongZHiTextField.text = @"其他";
    _chongZHiTextField.delegate= self;
    _chongZHiTextField.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:_chongZHiTextField];
    
    //选择支付方式
    NSMutableArray* buttons = [NSMutableArray arrayWithCapacity:2];
    CGRect btnRect = CGRectMake(30 * KscreenWidth, 355 * KscreenHeight + NAVIGATION_BAR_HEIGHT, (ScreenWidth - 60 * KscreenWidth)/2, 50 * KscreenHeight);
    for (NSString* optionTitle in @[@"微信支付", @"支付宝支付", @"银行卡支付"]) {
        RadioButton* btn = [[RadioButton alloc] initWithFrame:btnRect];
        [btn addTarget:self action:@selector(onRadioButtonValueChanged:) forControlEvents:UIControlEventValueChanged];
        if (iPhoneX) {
            btnRect.origin.x += 110 * KscreenWidth;
        }else{
            btnRect.origin.x += 125 * KscreenWidth;
        }
        
        [btn setTitle:optionTitle forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
        btn.titleLabel.font = [UIFont boldSystemFontOfSize:15 * KscreenWidth];
        [btn setImage:[UIImage imageNamed:@"椭圆1"] forState:UIControlStateNormal];
        [btn setImage:[UIImage imageNamed:@"椭圆2"] forState:UIControlStateSelected];
        btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        btn.titleEdgeInsets = UIEdgeInsetsMake(0, 6, 0, 0);
        
        [self.view addSubview:btn];
        [buttons addObject:btn];
    }
    [buttons[0] setGroupButtons:buttons]; // Setting buttons into the group
    
    //默认微信支付
    _ZhiFuFangShi = 1;
    [buttons[0] setSelected:YES];
    
    
    UILabel *lable1 = [[UILabel alloc]initWithFrame:CGRectMake(10 * KscreenWidth, Screenheight - 170 * KscreenHeight, ScreenWidth - 20 * KscreenWidth, 20 * KscreenHeight)];
    lable1.text = @"点击充值，即表示已阅读并同意充值协议";
    lable1.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:lable1];
    
    //创建 NSMutableAttributedString
    NSMutableAttributedString *attributedStr01 = [[NSMutableAttributedString alloc] initWithString: lable1.text];
    //给所有字符设置字体为Zapfino，字体高度为15像素
    [attributedStr01 addAttribute: NSFontAttributeName value: [UIFont fontWithName: @"Zapfino" size: 15 * KscreenWidth] range: NSMakeRange(0, lable1.text.length)];
    //分段控制，第5个字符开始的3个字符，即第5、6、7字符设置为红色
    [attributedStr01 addAttribute: NSForegroundColorAttributeName value: [UIColor redColor] range: NSMakeRange(14, 4)];
    
    //赋值给显示控件label01的 attributedText
    lable1.attributedText = attributedStr01;
    
    
    
//    UIButton *btnn = [UIButton buttonWithType:(UIButtonTypeCustom)];
//    btnn.frame = CGRectMake(ScreenWidth - 160 * KscreenWidth, Screenheight - 170 * KscreenHeight, 100 * KscreenWidth, 20 * KscreenHeight);
//    [btnn setTitle:@"充值协议" forState:0];
//    btnn.font = [UIFont systemFontOfSize:15 * KscreenWidth];
//    [btnn setTitleColor:[UIColor redColor] forState:0];
//    [self.view addSubview:btnn];
    
    UIButton *goChongZHi = [UIButton buttonWithType:(UIButtonTypeCustom)];
    goChongZHi.frame = CGRectMake(20 * KscreenWidth, Screenheight - 140 * KscreenHeight,ScreenWidth - 40 * KscreenWidth, 50 * KscreenHeight);
    [goChongZHi setTitle:@"去充值" forState:0];
    goChongZHi.backgroundColor = ZhuTiColor;
    goChongZHi.font = [UIFont systemFontOfSize:18 * KscreenWidth];
    [goChongZHi setTitleColor:[UIColor whiteColor] forState:0];
    
    [goChongZHi addTarget:self action:@selector(quchongZhiAction) forControlEvents:(UIControlEventTouchUpInside)];
    
    [self.view addSubview:goChongZHi];
}


//选择男女的方法
-(void) onRadioButtonValueChanged:(RadioButton*)sender
{
    if(sender.selected) {
        if ([sender.titleLabel.text isEqualToString:@"微信支付"]) {
            _ZhiFuFangShi = 1;
        }
        if ([sender.titleLabel.text isEqualToString:@"支付宝支付"]) {
            _ZhiFuFangShi = 2;
        }
        if ([sender.titleLabel.text isEqualToString:@"银行卡支付"]) {
            _ZhiFuFangShi = 3;
        }
    }
}


-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [_chongZHiTextField resignFirstResponder];
}

-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    _chongZHiTextField.text = @"";

}


-(void)textFieldDidEndEditing:(UITextField *)textField
{
    
    _chongZHiTextField.text = [NSString stringWithFormat:@"%@学豆",textField.text];
    
    if ([_chongZHiTextField.text isEqualToString:@"学豆"]) {
        _chongZHiTextField.text = @"其他";
    }else{
        _money = textField.text;
        _xuanzhong = @"";
        _chongZHiTextField.backgroundColor = ZhuTiColor;
        _chongZHiTextField.textColor = [UIColor whiteColor];
        [self.collectionView reloadData];
        
    }
    
}



#pragma mark 必须实现的方法
//每分区有多少个item
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{

    return _dataArray.count;
}

//每个item上面现实的内容
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    //从重用池里面获取cell
    ChongzhiTableViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ChongzhiTableViewCell" forIndexPath:indexPath];
    
    cell.btn.text = _dataArray[indexPath.row];

        if ([cell.btn.text isEqualToString: _xuanzhong ]){
            cell.btn.backgroundColor = ZhuTiColor;
            cell.btn.textColor = [UIColor whiteColor];
        }else{
            cell.btn.backgroundColor  = hui1Color;
            cell.btn.textColor = hui8Color;
        }

    
    return cell;
    
}


//设置分区数
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}


//点击item触发的事件
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{

        _xuanzhong = _dataArray[indexPath.row];
    
       _chongZHiTextField.backgroundColor = hui1Color;
       _chongZHiTextField.textColor = hui8Color;
    
    if (indexPath.row == 0) {
        _money = @"100";
    }else if (indexPath.row == 1){
        
        _money = @"50";
    }else if (indexPath.row == 2){
        
        _money = @"20";
    }else if (indexPath.row == 3){
        
        _money = @"10";
    }
    
     [_chongZHiTextField resignFirstResponder];
    
        [self.collectionView reloadData];
    

}

//返回分区内边距的上左下右的距离
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(0 * KscreenWidth, 20 * KscreenHeight, 0 * KscreenWidth, 20 * KscreenHeight);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
